import { RouteRecordRaw } from 'vue-router'
import { IBreadType } from '@/base-ui/breadcrumb/types'

//第一个菜单页面
let firstMenu: any = null

export function mapMenusToRoutes(userMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []
  //1.先加载默认的所有routes
  const allRoutes: RouteRecordRaw[] = []
  const routeFiles = require.context('@/router/main', true, /\.ts/)
  routeFiles.keys().forEach((key) => {
    const route = require('@/router/main' + key.split('.')[1])
    allRoutes.push(route.default)
  })
  // console.log(allRoutes)

  //2.根据菜单获取需要的路由
  const _recurseGetRoute = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 2) {
        const route = allRoutes.find((route) => route.path === menu.url)
        if (route) {
          routes.push(route)
          if (!firstMenu) {
            //拿到第一个菜单页面
            firstMenu = route.path
          }
        }
      } else {
        _recurseGetRoute(menu.children)
      }
    }
  }
  _recurseGetRoute(userMenus)
  return routes
}

//根据当前路径查找对应的菜单
export function pathMapToMenu(userMenus: any[], currentPath: string): any {
  for (const menu of userMenus) {
    if (menu.type === 1) {
      const findMenu = pathMapToMenu(menu.children ?? [], currentPath)
      if (findMenu) {
        return findMenu
      }
    } else if (menu.type === 2 && menu.url === currentPath) {
      return menu
    }
  }
}

//根据url获取breadcrumb

export function pathToBreadcrumbs(url: string, userMenus: any[]): IBreadType[] {
  const breadcrumbs: IBreadType[] = []

  function _recurseGetBreadcrumb(menus: any[]) {
    for (const menu of menus) {
      if (url === menu.url) {
        breadcrumbs.push({ name: menu.name, path: menu.url })
        break
      } else if (url.includes(menu.url)) {
        breadcrumbs.push({ name: menu.name, path: menu.url })
        _recurseGetBreadcrumb(menu.children)
      } else {
        continue
      }
    }
  }

  _recurseGetBreadcrumb(userMenus)
  // console.log(breadcrumbs)
  return breadcrumbs
}

//根据用户菜单获取用户权限
export function mapMenusToPermissions(userMenus: any[]) {
  const permissions: string[] = []

  const _recurseGetPermissions = (userMenus: any[]) => {
    for (const menu of userMenus) {
      if (menu.type === 1 || menu.type === 2) {
        _recurseGetPermissions(menu.children ?? [])
      } else if (menu.type === 3) {
        permissions.push(menu.permission)
      }
    }
  }
  _recurseGetPermissions(userMenus)
  return permissions
}

export function menuMapLeafKeys(menuList: any[]) {
  const leafKeys: number[] = []

  const _recurseGetLeaf = (menuList: any[]) => {
    for (const menu of menuList) {
      if (menu.children) {
        _recurseGetLeaf(menu.children)
      } else {
        leafKeys.push(menu.id)
      }
    }
  }

  _recurseGetLeaf(menuList)
  return leafKeys
}

export { firstMenu }
